package com.example.demo.servlet;

/**
 * 负责流程控制 和 页面跳转 login.jsp页面
 */

import com.example.demo.bean.Admin;
import com.example.demo.dao.AdminDaoImpl;
import com.example.demo.service.AdminService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/login-admin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        AdminService adminService = new AdminService();
        String status = req.getParameter("status");
        Admin admin = adminService.adminLoginService(new Admin(username, password));
        if(status != null) {
            Cookie[] cookies = req.getCookies();
            for (Cookie c : cookies) {
                if(c.getName().equals("user")) {
                    c.setValue(null);
                    resp.addCookie(c);
                    resp.sendRedirect("login.jsp");
                    return;
                }
            }
        }
        if(admin != null) {
            Cookie pageCookie1 = new Cookie("pageStart","0");
            resp.addCookie(pageCookie1);
            Cookie user = new Cookie("user",username);
            resp.addCookie(user);
            req.setAttribute("type","ref");
            req.getRequestDispatcher("m-servlet").forward(req,resp);
        }else {
            req.setAttribute("res", "用户名或密码错误！");
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(req,resp);
        }
    }
}
